package com.linwen.javase.thread;


/**以卖票场景为例
 * @author : linwen
 * @date : 下午7:05 2021/1/10
 * 实现runnable方法用同步代码块方式
 */
public class 线程锁1 {

    public static void main(String[] args) {
        //没有锁的情况,会有重票，错票的情况
        Window window = new Window();
        Thread t1 = new Thread(window);
        Thread t2 = new Thread(window);
        Thread t3 = new Thread(window);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
        //方式1：同步代码块
        /**
         * 将需要同步的代码块放在synchronized中
         * synchronized(同步监视器/锁){
         *     //code
         * }
         * 锁的要求：多个线程需要使用同一把锁
         */
    }
}
class Window implements Runnable{
    private int ticket = 100;
    Lock lock = new Lock();
    @Override
    public void run() {
        while (true){
            //开发中将非同步方法执行在同步执行前
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //开发中通常用this
            //synchronized (lock){
            synchronized (this){
                if(ticket>0){

                    System.out.println(Thread.currentThread().getName()+"=="+ticket);
                    ticket--;
                }else{
                    break;
                }

            }
        }
    }
}
class Lock{

}
